<?php

namespace app\api\model;


use app\admin\model\Config;
use app\shopapi\model\Shop;
use fast\Http;

class Pay
{
    protected $merchant_no = 'M51112404';

    protected $secret_key = '958dd682802c794a94431ae0b9ec4e9b';

    protected $api = 'https://service.eswhyf.com/unipay/';

    protected $appid;

    public function __construct()
    {
        $AppModel = new \app\admin\model\Config();
        $app = $AppModel->find(1);
        $this->appid = $app->mini_app_id;
    }

    public function calculate_amount($commission_rate,$price)
    {
        $amount = (100-$commission_rate)/100*$price;

        return $amount;
    }



    //聚合收银台下单接口
    public function unipay($order_no,$title,$trans_type,$total_fee,$notice_url)
    {
        $url = $this->api.'unipay/pay';

        $ip = request()->ip();

        $data = [
            'order_no'=>$order_no,
            'title'=>$title,//订单描述
            'trans_type'=>$trans_type,//交易类型 wxpay: 微信支付 alipay: 支付宝支付
            'total_fee'=>$total_fee,//订单金额，单位元。例如：1分 = 0.01
            'ip'=>$ip,
            'notice_url'=>$notice_url,
            //'timeout_express'=>'600'
        ];

        $pre_data = $this->signature($data);

        $res = Http::sendRequest($url,$pre_data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }

    }

    //统一下单
    public function pay($order_no,$title,$price,$openid,$paytype,$notice_url,$shop_id)
    {
        //$request = \think\Request::instance();

        $url = $this->api.'order/pay';

        $ip = request()->ip();

        $shop = Shop::where(['shop_id'=>$shop_id])->field('shop_id,commission_rate,merchant_no')->find();

        $amount = $this->calculate_amount($shop['commission_rate'],$price);

        $divide_config = [
            [
                'member_no'=>$shop['merchant_no'],
                'amount'=>$amount
            ]
        ];

        $data = [
            'order_no'=>$order_no,
            'title'=>$title,
            'jspay_flag'=>1,
            'trans_type'=>$paytype,
            'total_fee'=>$price,
            'ip'=>$ip,
            'appid'=>$this->appid,
            'openid'=>$openid,
            'notice_url'=>$notice_url,
            'divide_config'=>$divide_config
        ];
        dump($data);
        $pre_data = $this->signature($data);

        $res = Http::sendRequest($url,$pre_data);
        dump($res);die;
        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            return $res['data'];
        } else {
            throw new \Exception($result['msg']);
        }

    }

    //订单查询接口
    public function query($order_info)
    {
        $url = $this->api.'query/order';

        $data = [
            'order_no'=>$order_info['order_no'],
        ];

        $res = Http::sendRequest($url,$data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }

    }

    //订单退款接口
    public function refund($order_no,$amount,$shop_id)
    {
        $url = $this->api.'refund/order';

        $shop = Shop::where(['shop_id'=>$shop_id])->field('shop_id,commission_rate,merchant_no')->find();

        $price = $this->calculate_amount($shop['commission_rate'],$amount);

        $refund_config = [
            [
                'member_no'=>$shop['merchant_no'],
                'amount'=>$price
            ]
        ];

        $data = [
            'order_no'=>$order_no,
            'amount'=>$amount,
            //'refund_config'=>$refund_config
        ];

        $pre_data = $this->signature($data);

        $res = Http::sendRequest($url,$pre_data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            return [
                'code'=>1,
                'msg'=>'success'
                //'data'=>$result['data']
            ];
            //return $res['data'];
        } else {
            return [
                'code'=>0,
                'msg'=>$result['msg']
            ];
            //throw new \Exception($result['msg']);
        }

    }

    /**
     * 签名
     * @param array $data
     * @return array
     * @author cfn <cfn@leapy.cn>
     * @date 2021/11/9
     */
    protected function signature(array $data)
    {
        $pre_data = [
            'data' => json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
            'merchant_no' => $this->merchant_no,
            'nonce' => self::getRandomStr(16),
            'timestamp' => time(),
            'version' => '1.0',
        ];
        $pre_data['signature'] = self::createSignature($pre_data);
        return $pre_data;
    }

    /**
     * 创建签名字符串
     * @param $data
     * @return string
     * @author cfn <cfn@leapy.cn>
     * @date 2021/11/9
     */
    protected function createSignature($data)
    {
        // 1. 预签名数组 注意按照ascii排序
        ksort($data);
        // 2. 对数据进行k=v拼接并用&连接,内容为空的除外，例如：a=1&b=2
        $pre_str = '';
        foreach($data as $k => $v)
        {
            // 空值不参与签名
            !empty($v) && $pre_str .= $k . "=" . $v . "&";
        }
        // 3. 将auth_key拼接到最后边
        $pre_str .= 'secret_key='.$this->secret_key;
        // 4. 对数据进行md5加密，并转大写
        return strtoupper(md5($pre_str));
    }

    /**
     * 随机字符串
     * @param $len
     * @return string
     * @author cfn <cfn@leapy.cn>
     * @date 2021/11/9
     */
    protected function getRandomStr($len)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
}